package com.chj.controller;

import com.chj.vo.Product;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * 通过restTemplate访问product服务
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerProductSecurityController {
    // 普通方式访问product服务接口
//    public static final String PRODUCT_GET_URL = "http://localhost:8080/prodcut/get/";
//    public static final String PRODUCT_LIST_URL="http://localhost:8080/prodcut/list/";
//    public static final String PRODUCT_ADD_URL = "http://localhost:8080/prodcut/add/";
    // TODO 通过使用ribbon访问product服务
    public static final String PRODUCT_GET_URL = "http://SPRINGCLOUD-MICRO-PRODUCT/prodcut/get/";
    public static final String PRODUCT_LIST_URL= "http://SPRINGCLOUD-MICRO-PRODUCT/prodcut/list/";
    public static final String PRODUCT_ADD_URL = "http://SPRINGCLOUD-MICRO-PRODUCT/prodcut/add/";
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private HttpHeaders httpHeaders;
    // 服务提供方的信息获取
    @Resource
    private LoadBalancerClient loadBalancerClient;
    /**
     * 添加了spring security以后，访问接口需要密码验证，需要在请求头HttpHeaders中添加验证信息
     */
    @RequestMapping("/product/get2")
    public Object getProduct2(long id) {
        // 获取服务提供方的信息
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("SPRINGCLOUD-MICRO-PRODUCT") ;
        System.out.println("【*** ServiceInstance ***】host = " + serviceInstance.getHost()
                + "：port = " + serviceInstance.getPort()+ "：serviceId = " + serviceInstance.getServiceId());
        Product product = restTemplate.exchange(PRODUCT_GET_URL + id,HttpMethod.GET,
                new HttpEntity<Object>(httpHeaders), Product.class).getBody();
        return  product;
    }
    @RequestMapping("/product/list2")
    public  Object listProduct2() {
        List<Product> list = restTemplate.exchange(PRODUCT_LIST_URL,HttpMethod.GET,
                new HttpEntity<Object>(httpHeaders), List.class).getBody();
        return  list;
    }
    @RequestMapping("/product/add2")
    public Object addPorduct2(Product product) {
        Boolean result = restTemplate.exchange(PRODUCT_ADD_URL, HttpMethod.POST,
                new HttpEntity<Object>(product,httpHeaders), Boolean.class).getBody();
        return  result;
    }
}